<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

use DB;

class Commanager extends Model
{
    //
    protected $table = 'commanager';
    public $timestamps = false;

    public function addAll(Array $data)
 	{
      $rs = DB::table($this->getTable())->insert($data);
      return $rs;
  	}
     /*批量更新(case when使用注意长度)*/
    public function updateAll(Array $data) 
    {
        try {
            $firstRow = current($data);
            $updateColumn = array_keys($firstRow);
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
            foreach($updateColumn as $k=>$v) {
                if($v==$referenceColumn) {
                    unset($updateColumn[$k]);
                }
            }
            
            // 拼接sql语句
            $updateSql = "UPDATE " . $this->table . " SET ";
            $sets  = [];
            $bindings = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($data as $row) {
                     $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                     $bindings[] = $row[$referenceColumn];
                     $bindings[] = $row[$uColumn];
                }
                $setSql .= " END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn = collect($data)->pluck($referenceColumn)->values()->all();
            $bindings = array_merge($bindings, $whereIn);
            $whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            // 传入预处理sql语句和对应绑定数据
            return DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
           return false;
        }  
    }
}
